<template>
  <div class="second-hand-management">
    <el-card>
      <div slot="header" class="card-header">
        <span class="card-title">二手商品管理</span>
        <el-button type="primary" @click="handleAdd" class="add-button">
          <i class="el-icon-plus"></i>
          发布商品
        </el-button>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20" class="search-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索商品名称或描述"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select 
              v-model="searchForm.categoryId" 
              placeholder="选择类别" 
              clearable 
              filterable
              :loading="categoryLoading"
              @focus="handleCategorySelectFocus"
              style="width: 100%"
            >
              <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.categoryName"
                :value="category.id"
              />
            </el-select>
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 100%">
              <el-option label="在售" value="on_sale" />
              <el-option label="已售出" value="sold" />
              <el-option label="已下架" value="off_shelf" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 商品列表 -->
      <el-table
        :data="productList"
        v-loading="loading"
        stripe
        border
        size="medium"
        style="width: 100%"
        :fit="true"
      >
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column label="商品图片" width="100" align="center">
          <template slot-scope="scope">
            <el-image
              v-if="getFirstImage(scope.row.images)"
              :src="getFirstImage(scope.row.images)"
              :preview-src-list="getImageList(scope.row.images)"
              fit="cover"
              class="product-thumbnail"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div v-else class="no-image">
              <i class="el-icon-picture-outline"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类别" width="100" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template slot-scope="scope">
            <span class="price-text">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.originalPrice" style="text-decoration: line-through; color: #909399;">
              ¥{{ scope.row.originalPrice }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="成色" width="80" align="center">
          <template slot-scope="scope">
            {{ getConditionName(scope.row.condition) }}
          </template>
        </el-table-column>
        <el-table-column prop="sellerName" label="卖家" width="100" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览" width="80" align="center" />
        <el-table-column prop="createdAt" label="发布时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button size="mini" @click="handleView(scope.row)" icon="el-icon-view">查看</el-button>
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)" trigger="click">
                <el-button size="mini">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item 
                    v-if="scope.row.status === 'on_sale'" 
                    command="off_shelf"
                  >
                    <i class="el-icon-download"></i>
                    下架
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status === 'off_shelf'" 
                    command="on_sale"
                  >
                    <i class="el-icon-upload2"></i>
                    上架
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="scope.row.status !== 'sold'" 
                    command="sold"
                  >
                    <i class="el-icon-circle-check"></i>
                    标记已售
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <i class="el-icon-delete"></i>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 商品详情/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        :model="productForm"
        :rules="productRules"
        ref="productForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品类别" prop="categoryId">
              <el-select 
                v-model="productForm.categoryId" 
                placeholder="请选择类别" 
                filterable
                :loading="categoryLoading"
                @focus="handleCategorySelectFocus"
                style="width: 100%"
              >
                <el-option
                  v-for="category in categoryOptions"
                  :key="category.id"
                  :label="category.categoryName"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input-number 
                v-model="productForm.price" 
                :min="0" 
                :precision="2"
                placeholder="请输入价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原价">
              <el-input-number 
                v-model="productForm.originalPrice" 
                :min="0" 
                :precision="2"
                placeholder="原价（选填）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成色" prop="condition">
              <el-select v-model="productForm.condition" placeholder="请选择成色" style="width: 100%">
                <el-option label="全新" value="brand_new" />
                <el-option label="九成新" value="like_new" />
                <el-option label="八成新" value="very_good" />
                <el-option label="七成新" value="good" />
                <el-option label="六成新及以下" value="acceptable" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卖家姓名" prop="sellerName">
              <el-input v-model="productForm.sellerName" placeholder="请输入卖家姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="productForm.contactInfo" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易地点" prop="location">
              <el-input v-model="productForm.location" placeholder="请输入交易地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="productForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="在售" value="on_sale" />
                <el-option label="已售出" value="sold" />
                <el-option label="已下架" value="off_shelf" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品图片">
          <el-input 
            v-model="productForm.images" 
            type="textarea" 
            :rows="2"
            placeholder="请输入图片URL，多个URL用逗号分隔"
          />
          <div class="form-tip">提示：输入图片URL地址，多个地址用英文逗号分隔</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="900px"
      :show-close="false"
      class="product-detail-dialog"
    >
      <div slot="title" class="dialog-header">
        <div class="header-content">
          <div class="header-info">
            <h3 class="product-title">{{ currentProduct ? currentProduct.productName : '' }}</h3>
            <div class="product-meta">
              <el-tag 
                v-if="currentProduct"
                :type="getStatusType(currentProduct.status)" 
                size="medium"
                class="status-tag"
              >
                {{ getStatusName(currentProduct.status) }}
              </el-tag>
              <span class="product-id">ID: {{ currentProduct ? currentProduct.id : '' }}</span>
            </div>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="small" 
              icon="el-icon-edit"
              @click="handleEditFromDetail"
              plain
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              icon="el-icon-close"
              @click="detailDialogVisible = false"
              circle
            />
          </div>
        </div>
      </div>

      <div v-if="currentProduct" class="product-detail-content">
        <!-- 商品图片 -->
        <div v-if="getImageList(currentProduct.images).length > 0" class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-picture"></i>
            商品图片
          </h4>
          <div class="product-images">
            <el-image
              v-for="(image, index) in getImageList(currentProduct.images)"
              :key="index"
              :src="image"
              :preview-src-list="getImageList(currentProduct.images)"
              fit="cover"
              class="product-image-item"
            >
              <div slot="error" class="image-error">
                <i class="el-icon-picture-outline"></i>
                <span>加载失败</span>
              </div>
            </el-image>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-info"></i>
            基本信息
          </h4>
          <div class="detail-grid">
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">商品名称</label>
                  <div class="field-value">
                    <i class="el-icon-goods"></i>
                    {{ currentProduct.productName }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">商品类别</label>
                  <div class="field-value">
                    <i class="el-icon-folder"></i>
                    {{ currentProduct.categoryName || '未分类' }}
                  </div>
                </div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">售价</label>
                  <div class="field-value price-value">
                    <i class="el-icon-money"></i>
                    ¥{{ currentProduct.price }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">原价</label>
                  <div class="field-value">
                    <i class="el-icon-price-tag"></i>
                    {{ currentProduct.originalPrice ? `¥${currentProduct.originalPrice}` : '未填写' }}
                  </div>
                </div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">成色</label>
                  <div class="field-value">
                    <i class="el-icon-star-on"></i>
                    {{ getConditionName(currentProduct.condition) }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">交易地点</label>
                  <div class="field-value">
                    <i class="el-icon-location-outline"></i>
                    {{ currentProduct.location || '未指定' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品描述 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-document"></i>
            商品描述
          </h4>
          <div class="description-content">
            <p class="description-text">{{ currentProduct.description || '暂无描述' }}</p>
          </div>
        </div>

        <!-- 卖家信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-user-solid"></i>
            卖家信息
          </h4>
          <div class="detail-grid">
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">卖家姓名</label>
                  <div class="field-value">
                    <i class="el-icon-user"></i>
                    {{ currentProduct.sellerName || '未知' }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">联系方式</label>
                  <div class="field-value">
                    <i class="el-icon-phone"></i>
                    {{ currentProduct.contactInfo || '未填写' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-data-analysis"></i>
            统计信息
          </h4>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-icon view-icon">
                <i class="el-icon-view"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ currentProduct.viewCount || 0 }}</div>
                <div class="stat-label">浏览次数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon time-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ getDaysOnSale(currentProduct.createdAt) }}</div>
                <div class="stat-label">在售天数</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="footer-stats">
          <span class="footer-text">发布于 {{ formatDate(currentProduct ? currentProduct.createdAt : '') }}</span>
        </div>
        <div class="footer-actions">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail" icon="el-icon-edit">
            编辑商品
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "SecondHandManagement",
  data() {
    return {
      loading: false,
      submitLoading: false,
      categoryLoading: false,
      productList: [],
      categoryOptions: [],
      searchForm: {
        keyword: "",
        categoryId: "",
        status: ""
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      dialogTitle: "",
      isEdit: false,
      currentProduct: null,
      productForm: {
        id: null,
        productName: "",
        description: "",
        categoryId: "",
        price: 0,
        originalPrice: null,
        condition: "good",
        sellerName: "",
        contactInfo: "",
        location: "",
        status: "on_sale",
        images: ""
      },
      productRules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入商品描述", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "请选择商品类别", trigger: "change" }
        ],
        price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        condition: [
          { required: true, message: "请选择商品成色", trigger: "change" }
        ],
        sellerName: [
          { required: true, message: "请输入卖家姓名", trigger: "blur" }
        ],
        contactInfo: [
          { required: true, message: "请输入联系方式", trigger: "blur" }
        ]
      }
    }
  },
  async created() {
    await this.loadCategoryOptions()
    await this.loadProductList()
  },
  methods: {
    async loadCategoryOptions(showMessage = false) {
      this.categoryLoading = true
      try {
        const response = await this.$http.get("/admin/second-hand-categories/options")
        if (response.data.code === 200) {
          this.categoryOptions = response.data.data || []
          if (showMessage && this.categoryOptions.length > 0) {
            this.$message.success(`成功加载 ${this.categoryOptions.length} 个类别`)
          }
        } else {
          throw new Error(response.data.message || '获取类别列表失败')
        }
      } catch (error) {
        console.error("加载类别选项失败:", error)
        if (showMessage) {
          this.$message.error('加载类别列表失败，使用默认数据')
        }
        // 使用模拟数据
        this.categoryOptions = [
          { id: 1, categoryName: "电子产品" },
          { id: 2, categoryName: "图书教材" },
          { id: 3, categoryName: "生活用品" },
          { id: 4, categoryName: "运动器材" },
          { id: 5, categoryName: "自行车" }
        ]
      } finally {
        this.categoryLoading = false
      }
    },

    handleCategorySelectFocus() {
      if (this.categoryOptions.length === 0 && !this.categoryLoading) {
        this.loadCategoryOptions()
      }
    },

    async loadProductList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/second-hand-products", { params })
        console.log("二手商品API响应:", response.data)
        if (response.data.code === 200) {
          // 处理不同的数据结构
          const data = response.data.data
          if (Array.isArray(data)) {
            this.productList = data
            this.pagination.total = data.length
          } else if (data && data.list) {
            this.productList = data.list
            this.pagination.total = data.total || data.list.length
          } else if (data && Array.isArray(data.records)) {
            this.productList = data.records
            this.pagination.total = data.total || data.records.length
          } else {
            this.productList = data || []
            this.pagination.total = Array.isArray(data) ? data.length : 0
          }
          console.log("二手商品数据:", this.productList)
          console.log("分页总数:", this.pagination.total)
        } else {
          console.error("API返回错误:", response.data.message)
          this.productList = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error("加载二手商品列表失败:", error)
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      this.productList = [
        {
          id: 1,
          productName: "iPhone 13 Pro 256G",
          description: "99新，无磕碰，原装配件齐全，因换新机出售",
          categoryName: "电子产品",
          categoryId: 1,
          price: 4500,
          originalPrice: 7999,
          condition: "like_new",
          sellerName: "张同学",
          contactInfo: "13800138000",
          location: "校内面交",
          status: "on_sale",
          viewCount: 156,
          images: "https://via.placeholder.com/400x400/667eea/ffffff?text=iPhone+13+Pro",
          createdAt: "2025-10-10T10:00:00"
        },
        {
          id: 2,
          productName: "高等数学教材（第七版）",
          description: "上下册全，有笔记，无缺页",
          categoryName: "图书教材",
          categoryId: 2,
          price: 30,
          originalPrice: 68,
          condition: "good",
          sellerName: "李同学",
          contactInfo: "13900139000",
          location: "图书馆门口",
          status: "on_sale",
          viewCount: 89,
          images: "https://via.placeholder.com/400x400/f56c6c/ffffff?text=Math+Book",
          createdAt: "2025-10-12T14:30:00"
        },
        {
          id: 3,
          productName: "电动自行车",
          description: "雅迪电动车，续航60公里，9成新",
          categoryName: "自行车",
          categoryId: 5,
          price: 1200,
          originalPrice: 2800,
          condition: "like_new",
          sellerName: "王同学",
          contactInfo: "13700137000",
          location: "北门",
          status: "sold",
          viewCount: 234,
          images: "https://via.placeholder.com/400x400/67c23a/ffffff?text=E-Bike",
          createdAt: "2025-10-08T09:15:00"
        }
      ]
      this.pagination.total = 3
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadProductList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        categoryId: "",
        status: ""
      }
      this.pagination.currentPage = 1
      this.loadProductList()
    },

    handleAdd() {
      this.dialogTitle = "发布二手商品"
      this.isEdit = false
      this.productForm = {
        id: null,
        productName: "",
        description: "",
        categoryId: "",
        price: 0,
        originalPrice: null,
        condition: "good",
        sellerName: "",
        contactInfo: "",
        location: "",
        status: "on_sale",
        images: ""
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = "编辑二手商品"
      this.isEdit = true
      this.productForm = {
        id: row.id,
        productName: row.productName,
        description: row.description,
        categoryId: row.categoryId,
        price: row.price,
        originalPrice: row.originalPrice,
        condition: row.condition,
        sellerName: row.sellerName,
        contactInfo: row.contactInfo,
        location: row.location,
        status: row.status,
        images: row.images || ""
      }
      this.dialogVisible = true
    },

    handleView(row) {
      this.currentProduct = row
      this.detailDialogVisible = true
    },

    handleEditFromDetail() {
      this.detailDialogVisible = false
      this.handleEdit(this.currentProduct)
    },

    async handleChangeStatus(row, newStatus) {
      const actionMap = {
        'on_sale': '上架',
        'off_shelf': '下架',
        'sold': '标记为已售'
      }
      const action = actionMap[newStatus]
      
      try {
        await this.$confirm(`确定要${action}该商品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.put(`/admin/second-hand-products/${row.id}/status`, {
          status: newStatus
        })
        
        if (response.data.code === 200) {
          this.$message.success(`${action}成功`)
          this.loadProductList()
        } else {
          this.$message.error(response.data.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${action}商品失败:`, error)
          this.$message.error(`${action}失败`)
        }
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该商品吗？删除后不可恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.delete(`/admin/second-hand-products/${row.id}`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.loadProductList()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商品失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      try {
        await this.$refs.productForm.validate()
        this.submitLoading = true

        const url = this.isEdit ? `/admin/second-hand-products/${this.productForm.id}` : '/admin/second-hand-products'
        const method = this.isEdit ? 'put' : 'post'
        
        const response = await this.$http[method](url, this.productForm)
        
        if (response.data.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '发布成功')
          this.dialogVisible = false
          this.loadProductList()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitLoading = false
      }
    },

    handleDialogClose() {
      this.$refs.productForm.resetFields()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadProductList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadProductList()
    },

    handleCommand(command, row) {
      switch (command) {
        case 'on_sale':
        case 'off_shelf':
        case 'sold':
          this.handleChangeStatus(row, command)
          break
        case 'delete':
          this.handleDelete(row)
          break
      }
    },

    getStatusType(status) {
      const statusMap = {
        on_sale: "success",
        sold: "info",
        off_shelf: "warning"
      }
      return statusMap[status] || "info"
    },

    getStatusName(status) {
      const statusMap = {
        on_sale: "在售",
        sold: "已售出",
        off_shelf: "已下架"
      }
      return statusMap[status] || "未知"
    },

    getConditionName(condition) {
      const conditionMap = {
        brand_new: "全新",
        like_new: "九成新",
        very_good: "八成新",
        good: "七成新",
        acceptable: "六成新及以下"
      }
      return conditionMap[condition] || condition
    },

    getDaysOnSale(createdAt) {
      if (!createdAt) return 0
      const created = new Date(createdAt)
      const now = new Date()
      const diff = now - created
      return Math.floor(diff / (1000 * 60 * 60 * 24))
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    },

    getFirstImage(images) {
      if (!images) return null
      try {
        // 尝试解析JSON数组格式
        const imageList = JSON.parse(images)
        if (Array.isArray(imageList) && imageList.length > 0) {
          return imageList[0]
        }
      } catch (e) {
        // 如果不是JSON格式，尝试按逗号分隔
        const imageList = images.split(',').map(img => img.trim()).filter(img => img)
        if (imageList.length > 0) {
          return imageList[0]
        }
      }
      return null
    },

    getImageList(images) {
      if (!images) return []
      try {
        // 尝试解析JSON数组格式
        const imageList = JSON.parse(images)
        if (Array.isArray(imageList)) {
          return imageList
        }
      } catch (e) {
        // 如果不是JSON格式，尝试按逗号分隔
        return images.split(',').map(img => img.trim()).filter(img => img)
      }
      return []
    }
  }
}
</script>

<style scoped>
.second-hand-management {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 搜索区域样式 */
.search-area {
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  padding: 16px;
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.second-hand-management ::v-deep .el-table {
  border: 1px solid #e4e7ed;
}

.second-hand-management ::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
}

/* 分页样式 */
.pagination-area {
  margin-top: 16px;
  text-align: right;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  padding: 6px 12px;
  font-size: 12px;
}

/* 表单提示 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 商品缩略图样式 */
.product-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.product-thumbnail:hover {
  transform: scale(1.1);
}

.image-slot,
.no-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 24px;
}

/* 商品图片展示 */
.product-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  padding: 4px;
}

.product-image-item {
  width: 100%;
  height: 150px;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image-item:hover {
  border-color: #409eff;
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #c0c4cc;
  font-size: 14px;
  gap: 8px;
}

.image-error i {
  font-size: 32px;
}

/* 商品详情对话框样式 */
.product-detail-dialog ::v-deep .el-dialog__header {
  padding: 0;
  border-bottom: 1px solid #ebeef5;
}

.product-detail-dialog ::v-deep .el-dialog__body {
  padding: 0;
  max-height: 70vh;
  overflow-y: auto;
}

.product-detail-dialog ::v-deep .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.dialog-header {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.header-info {
  flex: 1;
}

.product-title {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
  line-height: 1.3;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-tag {
  font-weight: 500;
}

.product-id {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-actions .el-button {
  color: white;
  border-color: rgba(255, 255, 255, 0.3);
}

.header-actions .el-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.5);
}

.product-detail-content {
  padding: 0;
}

.detail-section {
  padding: 20px;
  border-bottom: 1px solid #f0f2f5;
}

.detail-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #409eff;
}

.detail-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 20px;
}

.detail-col {
  flex: 1;
}

.detail-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-label {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.field-value {
  font-size: 14px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #e4e7ed;
}

.field-value i {
  color: #909399;
  font-size: 16px;
}

.price-value {
  border-left-color: #f56c6c;
  background-color: #fef0f0;
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}

.price-value i {
  color: #f56c6c;
}

.description-content {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border-left: 4px solid #409eff;
}

.description-text {
  margin: 0;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.stat-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
}

.view-icon {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.time-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.status-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-stats {
  flex: 1;
}

.footer-text {
  color: #909399;
  font-size: 13px;
}

.footer-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .second-hand-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-area {
    padding: 12px;
  }
  
  .search-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-buttons {
    justify-content: center;
    width: 100%;
  }
  
  .pagination-area {
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }

  .product-detail-dialog {
    width: 95% !important;
    margin: 0 auto;
  }

  .header-content {
    flex-direction: column;
    gap: 15px;
  }

  .header-actions {
    align-self: stretch;
    justify-content: space-between;
  }

  .detail-row {
    flex-direction: column;
    gap: 12px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .footer-actions {
    justify-content: center;
  }

  .product-images {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 8px;
  }

  .product-image-item {
    height: 120px;
  }
}
</style>

